<template>
  <div class="timer-container">
    <!-- 顶部：倒计时和工作时长调整 -->
    <div class="timer-main">
      <!-- 左侧调整按钮 -->
      <div class="adjust-controls left" v-if="!isRunning && !isPaused">
        <button @click="adjustWorkDuration(-5)" class="btn-adjust" title="-5分钟">⏪</button>
        <button @click="adjustWorkDuration(-1)" class="btn-adjust" title="-1分钟">➖</button>
      </div>
      <div class="adjust-controls left placeholder" v-else></div>

      <!-- 中间时间显示 -->
      <div class="timer-display">
        <div class="time">{{ formatTime(remainingTime) }}</div>
        <div class="status">{{ statusText }}</div>
      </div>

      <!-- 右侧调整按钮 -->
      <div class="adjust-controls right" v-if="!isRunning && !isPaused">
        <button @click="adjustWorkDuration(1)" class="btn-adjust" title="+1分钟">➕</button>
        <button @click="adjustWorkDuration(5)" class="btn-adjust" title="+5分钟">⏩</button>
      </div>
      <div class="adjust-controls right placeholder" v-else></div>
    </div>

    <!-- 中部：休息时长设置 -->
    <div class="break-settings" v-if="!isRunning && !isPaused">
      <span class="setting-label">休息时长:</span>
      <div class="break-controls">
        <button @click="adjustBreakDuration(-1)" class="btn-icon-small" title="-1分钟">➖</button>
        <span class="setting-value">{{ breakDuration }}</span>
        <button @click="adjustBreakDuration(1)" class="btn-icon-small" title="+1分钟">➕</button>
      </div>
      <span class="setting-unit">分钟</span>
    </div>
    
    <!-- 底部控制按钮 -->
    <div class="timer-controls">
      <button 
        v-if="!isRunning && !isPaused" 
        @click="startTimer" 
        class="btn btn-primary"
      >
        开始专注
      </button>
      <button 
        v-if="isRunning" 
        @click="pauseTimer" 
        class="btn btn-secondary"
      >
        暂停
      </button>
      <button 
        v-if="isPaused" 
        @click="resumeTimer" 
        class="btn btn-primary"
      >
        继续
      </button>
      <button 
        v-if="isRunning || isPaused" 
        @click="resetTimer" 
        class="btn btn-secondary"
      >
        重置
      </button>
    </div>

    <!-- 底部：分心应用设置 -->
    <div class="distraction-panel">
      <!-- 左侧：应用列表 -->
      <div class="list-section">
        <div class="section-header">已拦截应用</div>
        <div class="app-list-scroll">
          <div v-for="app in distractionApps" :key="app" class="app-tag-compact">
            <span>{{ app }}</span>
            <button @click="removeApp(app)" class="btn-remove-compact">×</button>
          </div>
          <div v-if="distractionApps.length === 0" class="empty-tip-compact">
            暂无拦截应用
          </div>
        </div>
      </div>

      <!-- 右侧：添加应用 -->
      <div class="add-section">
        <div class="section-header">添加新应用</div>
        <div class="add-controls-vertical">
          <input 
            v-model="newAppName" 
            @keyup.enter="addApp" 
            placeholder="输入应用名称..." 
            class="input-app-compact" 
          />
          <button @click="addApp" class="btn-add-compact">添加</button>
          <button @click="openAppSelector" class="btn-select-compact">从运行中选择</button>
        </div>
      </div>
    </div>

    <!-- 应用选择弹窗 -->
    <div v-if="showAppSelector" class="modal-overlay" @click.self="showAppSelector = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>选择运行中的应用</h3>
          <button @click="showAppSelector = false" class="btn-close">×</button>
        </div>
        <div class="modal-body">
          <div v-if="loadingApps" class="loading">加载中...</div>
          <div v-else-if="runningApps.length === 0" class="empty">未找到运行中的应用</div>
          <div v-else class="app-grid">
            <div 
              v-for="app in runningApps" 
              :key="app" 
              class="app-item"
              @click="selectRunningApp(app)"
            >
              {{ app }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';

console.log('Timer component loading...');

const remainingTime = ref(25 * 60); // 默认25分钟，单位：秒
const isRunning = ref(false);
const isPaused = ref(false);
const workDuration = ref(25); // 工作时长（分钟）
const breakDuration = ref(5); // 休息时长（分钟）
const distractionApps = ref([]); // 分心应用列表
const newAppName = ref('');
const showAppSelector = ref(false);
const runningApps = ref([]);
const loadingApps = ref(false);

let unlistenTimerTick = null;
let unlistenTimerComplete = null;
let unlistenWaterState = null;

const statusText = computed(() => {
  if (isRunning.value) return '专注中';
  if (isPaused.value) return '已暂停';
  return '准备开始';
});

const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
};

const saveSettings = async () => {
  try {
    await invoke('save_settings', {
      workDuration: workDuration.value,
      breakDuration: breakDuration.value,
      distractionApps: distractionApps.value
    });
  } catch (error) {
    console.error('保存设置失败:', error);
  }
};

const adjustWorkDuration = (delta) => {
  const newValue = workDuration.value + delta;
  if (newValue >= 1 && newValue <= 120) {
    workDuration.value = newValue;
    if (!isRunning.value && !isPaused.value) {
      remainingTime.value = newValue * 60;
    }
    saveSettings();
  }
};

const adjustBreakDuration = (delta) => {
  const newValue = breakDuration.value + delta;
  if (newValue >= 1 && newValue <= 60) {
    breakDuration.value = newValue;
    saveSettings();
  }
};

const addApp = () => {
  if (newAppName.value.trim() && !distractionApps.value.includes(newAppName.value.trim())) {
    distractionApps.value.push(newAppName.value.trim());
    newAppName.value = '';
    saveSettings();
  }
};

const removeApp = (app) => {
  distractionApps.value = distractionApps.value.filter(a => a !== app);
  saveSettings();
};

const openAppSelector = async () => {
  showAppSelector.value = true;
  loadingApps.value = true;
  runningApps.value = [];
  try {
    const apps = await invoke('get_running_apps');
    // 过滤掉已经在列表中的应用
    runningApps.value = apps.filter(app => !distractionApps.value.includes(app));
  } catch (error) {
    console.error('获取运行应用失败:', error);
  } finally {
    loadingApps.value = false;
  }
};

const selectRunningApp = (app) => {
  if (!distractionApps.value.includes(app)) {
    distractionApps.value.push(app);
    saveSettings();
    // 从列表中移除
    runningApps.value = runningApps.value.filter(a => a !== app);
  }
};

const startTimer = async () => {
  try {
    await invoke('start_timer', { duration: workDuration.value * 60 });
    // 状态更新将通过事件驱动，但为了UI即时响应，可以先设置
    isRunning.value = true;
    isPaused.value = false;
  } catch (error) {
    console.error('启动计时器失败:', error);
  }
};

const pauseTimer = async () => {
  try {
    await invoke('pause_timer');
    isRunning.value = false;
    isPaused.value = true;
  } catch (error) {
    console.error('暂停计时器失败:', error);
  }
};

const resumeTimer = async () => {
  try {
    await invoke('resume_timer');
    isRunning.value = true;
    isPaused.value = false;
  } catch (error) {
    console.error('恢复计时器失败:', error);
  }
};

const resetTimer = async () => {
  try {
    await invoke('reset_timer');
    isRunning.value = false;
    isPaused.value = false;
    remainingTime.value = workDuration.value * 60;
    await hideWaterAnimation();
  } catch (error) {
    console.error('重置计时器失败:', error);
  }
};

const handleTimerComplete = async () => {
  isRunning.value = false;
  isPaused.value = false;
  remainingTime.value = 0;
  
  // 播放提示音
  playNotificationSound();
  
  // 提示用户
  // alert('专注时间结束！'); // 移除 alert，因为它会阻塞
  // 可以考虑使用系统通知，但目前先只播放声音
  
  // 确保动画隐藏
  await hideWaterAnimation();
};

const playNotificationSound = () => {
  try {
    const AudioContext = window.AudioContext || window.webkitAudioContext;
    if (!AudioContext) return;
    
    const ctx = new AudioContext();
    const oscillator = ctx.createOscillator();
    const gainNode = ctx.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(ctx.destination);
    
    // 设置音色和频率
    oscillator.type = 'sine';
    oscillator.frequency.setValueAtTime(523.25, ctx.currentTime); // C5
    oscillator.frequency.exponentialRampToValueAtTime(1046.5, ctx.currentTime + 0.1); // C6
    
    // 设置音量包络
    gainNode.gain.setValueAtTime(0.3, ctx.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.5);
    
    oscillator.start();
    oscillator.stop(ctx.currentTime + 0.5);
  } catch (e) {
    console.error('播放提示音失败:', e);
  }
};

const loadSettings = async () => {
  try {
    const settings = await invoke('get_settings');
    if (settings) {
      workDuration.value = settings.work_duration || 25;
      breakDuration.value = settings.break_duration || 5;
      distractionApps.value = settings.distraction_apps || [];
      // 如果没有运行且没有暂停，重置时间显示
      if (!isRunning.value && !isPaused.value) {
        remainingTime.value = workDuration.value * 60;
      }
    }
  } catch (error) {
    console.error('加载设置失败:', error);
  }
};

const syncTimerStatus = async () => {
  try {
    const status = await invoke('get_timer_status');
    if (status) {
      remainingTime.value = status.remaining;
      isRunning.value = status.is_running;
      isPaused.value = status.is_paused;
    }
  } catch (error) {
    console.error('同步计时器状态失败:', error);
  }
};

const checkWaterAnimationState = async () => {
  try {
    const shouldShow = await invoke('get_water_animation_state');
    if (shouldShow) {
      await showWaterAnimation();
    } else {
      await hideWaterAnimation();
    }
  } catch (error) {
    console.error('检查水浸动画状态失败:', error);
  }
};

const showWaterAnimation = async () => {
  try {
    await invoke('create_overlay_window');
    console.log('显示水浸动画');
  } catch (error) {
    console.error('显示水浸动画失败:', error);
  }
};

const hideWaterAnimation = async () => {
  try {
    // 暂时通过后端关闭窗口（这里其实不需要显式调用关闭，因为后端逻辑会处理，但为了保险可以保留）
    // 但目前后端 create_overlay_window 负责创建，关闭逻辑主要在后端 window_monitor_loop 中
    // 前端主要是接收状态来决定是否需要提示用户，或者做一些前端的UI反馈
    // 如果需要强制关闭，可以调用 close_overlay_window
    await invoke('close_overlay_window');
    console.log('隐藏水浸动画');
  } catch (error) {
    console.error('隐藏水浸动画失败:', error);
  }
};

onMounted(async () => {
  console.log('Timer component mounted');
  
  // 1. 加载设置
  await loadSettings();
  
  // 2. 同步计时器状态（处理刷新页面或重新打开应用的情况）
  await syncTimerStatus();
  
  // 3. 检查是否需要显示水浸动画
  await checkWaterAnimationState();
  
  // 4. 注册事件监听
  
  // 监听倒计时更新
  unlistenTimerTick = await listen('timer-tick', (event) => {
    remainingTime.value = event.payload.remaining;
    // 收到 tick 说明正在运行
    if (!isRunning.value) isRunning.value = true;
    if (isPaused.value) isPaused.value = false;
  });
  
  // 监听倒计时结束
  unlistenTimerComplete = await listen('timer-complete', () => {
    handleTimerComplete();
  });

  // 监听水浸动画状态变更
  unlistenWaterState = await listen('water-animation-state', (event) => {
    const shouldShow = event.payload;
    if (shouldShow) {
      showWaterAnimation();
    } else {
      hideWaterAnimation();
    }
  });
});

onUnmounted(() => {
  if (unlistenTimerTick) unlistenTimerTick();
  if (unlistenTimerComplete) unlistenTimerComplete();
  if (unlistenWaterState) unlistenWaterState();
});
</script>


<style scoped>
.timer-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  padding: 1rem 2rem;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.timer-main {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  flex: 0 0 auto;
  margin-top: 2rem;
  margin-bottom: 1rem;
}

.adjust-controls {
  display: flex;
  gap: 0.5rem;
  width: 80px;
  justify-content: center;
  opacity: 0; /* 默认隐藏，hover时显示，或者一直显示但颜色淡 */
  transition: opacity 0.3s;
}

.timer-main:hover .adjust-controls {
  opacity: 1;
}

.adjust-controls.left {
  justify-content: flex-end;
  margin-right: 1.5rem;
}

.adjust-controls.right {
  justify-content: flex-start;
  margin-left: 1.5rem;
}

.adjust-controls.placeholder {
  visibility: hidden;
}

.btn-adjust {
  background: transparent;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  color: var(--color-text-secondary);
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-adjust:hover {
  background: var(--color-bg-hover);
  color: var(--color-primary);
  transform: scale(1.1);
}

.timer-display {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.time {
  font-size: 7rem;
  font-weight: 600;
  color: var(--color-primary);
  line-height: 1;
  font-variant-numeric: tabular-nums;
  letter-spacing: -2px;
  text-shadow: 0 2px 10px rgba(59, 130, 246, 0.1);
}

.status {
  font-size: 1.1rem;
  color: var(--color-text-secondary);
  margin-top: 0.5rem;
  letter-spacing: 2px;
  text-transform: uppercase;
}

.break-settings {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
  padding: 0.5rem 1.5rem;
  border-radius: 50px;
  background: var(--color-bg-hover); /* 更淡的背景 */
  flex: 0 0 auto;
}

.break-controls {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.btn-icon-small {
  background: white;
  border: 1px solid var(--color-border);
  cursor: pointer;
  font-size: 1rem;
  color: var(--color-text);
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.btn-icon-small:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
}

.setting-unit {
  font-size: 0.9rem;
  color: var(--color-text-secondary);
}

.distraction-panel {
  flex: 1;
  width: 100%;
  max-width: 600px;
  display: flex;
  flex-direction: row;
  gap: 1.5rem;
  background: transparent;
  border-top: 1px solid var(--color-border);
  padding: 1.5rem 0 0 0;
  margin-bottom: 1rem;
  overflow: hidden; 
}

.list-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0; /* 防止flex子项溢出 */
}

.add-section {
  flex: 0 0 200px;
  display: flex;
  flex-direction: column;
  border-left: 1px solid var(--color-border);
  padding-left: 1.5rem;
}

.section-header {
  font-size: 0.85rem;
  font-weight: 500;
  color: var(--color-text-secondary);
  margin-bottom: 0.8rem;
  text-align: left;
  opacity: 0.8;
}

.add-controls-vertical {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.input-app-compact {
  width: 100%;
  padding: 0.5rem 0.8rem;
  border: 1px solid var(--color-border);
  border-radius: 12px;
  font-size: 0.9rem;
  background: var(--color-bg);
  color: var(--color-text);
  transition: border-color 0.2s;
}

.input-app-compact:focus {
  outline: none;
  border-color: var(--color-primary);
}

.btn-add-compact {
  width: 100%;
  padding: 0.2rem;
  background: var(--color-bg-hover);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: 12px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-add-compact:hover {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
}

.btn-select-compact {
  width: 100%;
  padding: 0.2rem;
  background: transparent;
  color: var(--color-text-secondary);
  border: 1px dashed var(--color-border);
  border-radius: 12px;
  font-size: 0.8rem;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-select-compact:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
  background: var(--color-bg-hover);
}

.app-list-scroll {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: flex-start;
  gap: 0.5rem;
  padding-right: 0.5rem;
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal-content {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: 16px;
  width: 80%;
  max-width: 500px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.modal-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid var(--color-border);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.1rem;
  color: var(--color-text);
}

.btn-close {
  background: transparent;
  border: none;
  color: var(--color-text-secondary);
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0;
  line-height: 1;
}

.btn-close:hover {
  color: var(--color-text);
}

.modal-body {
  padding: 1.5rem;
  overflow-y: auto;
  flex: 1;
}

.loading, .empty {
  text-align: center;
  color: var(--color-text-secondary);
  padding: 2rem 0;
}

.app-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 0.8rem;
}

.app-item {
  background: var(--color-bg-hover);
  border: 1px solid transparent;
  border-radius: 8px;
  padding: 0.8rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.9rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.app-item:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
  transform: translateY(-2px);
}

.app-list-scroll::-webkit-scrollbar {
  width: 4px;
}
.app-list-scroll::-webkit-scrollbar-track {
  background: transparent;
}
.app-list-scroll::-webkit-scrollbar-thumb {
  background: var(--color-border);
  border-radius: 2px;
}

.app-tag-compact {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.3rem 0.6rem;
  background: var(--color-bg-hover);
  border: none;
  border-radius: 8px;
  font-size: 0.85rem;
  color: var(--color-text-secondary);
  transition: all 0.2s;
}

.app-tag-compact:hover {
  background: var(--color-border);
  color: var(--color-text);
}

.btn-remove-compact {
  background: transparent;
  border: none;
  color: var(--color-text-secondary);
  cursor: pointer;
  font-size: 1.1rem;
  padding: 0;
  line-height: 1;
  display: flex;
  opacity: 0.5;
}

.btn-remove-compact:hover {
  opacity: 1;
  color: var(--color-danger);
}

.empty-tip-compact {
  width: 100%;
  text-align: center;
  color: var(--color-text-secondary);
  font-size: 0.85rem;
  opacity: 0.6;
  margin-top: 0.5rem;
}

.timer-controls {
  display: flex;
  gap: 1.5rem;
  flex: 0 0 auto;
  padding-bottom: 1.5rem;
  justify-content: center;
  width: 100%;
}

.btn {
  border: none;
  border-radius: 50px;
  cursor: pointer;
  font-size: 1.1rem;
  font-weight: 500;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-primary {
  background: var(--color-primary);
  color: white;
  padding: 1rem 3rem;
  font-size: 1.3rem;
  box-shadow: 0 10px 20px -5px rgba(59, 130, 246, 0.4);
}

.btn-primary:hover {
  background: var(--color-primary-dark);
  transform: translateY(-2px);
  box-shadow: 0 15px 25px -5px rgba(59, 130, 246, 0.5);
}

.btn-secondary {
  background: var(--color-bg-hover);
  color: var(--color-text);
  padding: 0.8rem 2rem;
}

.btn-secondary:hover {
  background: var(--color-border);
}
</style>

